package cn.com.connext.scrm.web.rest;

import cn.com.connext.scrm.domain.master.OrderRecord;
import cn.com.connext.scrm.service.dto.JsonResult;
import cn.com.connext.scrm.service.mapper.OrderService;
import cn.com.connext.scrm.web.rest.errors.MyErrorCode;
import cn.com.connext.scrm.web.rest.req.*;
import com.alibaba.fastjson.JSON;
import com.connext.common.exception.ServiceException;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.ss.usermodel.Workbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;

/**
 * 积分商城配置 - 订单管理
 */
@RestController
@RequestMapping("/api/shopping/order")
public class OrderResource {

    private final Logger log = LoggerFactory.getLogger(OrderResource.class);

    @Autowired
    private OrderService orderService;


    /**
     * 创建订单列表
     */
    @PostMapping("/create")
    @ApiOperation(value = "创建订单管理", tags = {"订单列表"}, notes = "创建订单管理")
    public JsonResult save(@RequestBody OrderReq req) {
        log.info("创建订单管理，入参: {}", JSON.toJSONString(req));
        if (req == null) {
            throw new ServiceException(MyErrorCode.ERROR_INPUT);
        }
        return orderService.save(req);
    }


    /**
     * 查询订单列表
     */
    @PostMapping("/page")
    @ApiOperation(value = "查询订单", tags = {"订单列表"}, notes = "查询订单")
    public JsonResult page(@RequestBody OrderQueryReq req) {
        log.info("查询订单，入参: {}", JSON.toJSONString(req));
        if (req == null) {
            throw new ServiceException(MyErrorCode.ERROR_INPUT);
        }
        return orderService.page(req);
    }

    /**
     * 详情
     */
    @PostMapping("/detail")
    @ApiOperation(value = "查询订单详情", tags = {"查询订单详情"}, notes = "查询订单详情")
    public JsonResult detail(@RequestBody DeleteReq req) {
        log.info("查询订单详情，入参: {}", JSON.toJSONString(req));
        if (StringUtils.isBlank(req.getId())) {
            throw new ServiceException(MyErrorCode.ERROR_INPUT);
        }
        return orderService.detail(req.getId());
    }

    /**
     * 更新订单号和发货状态
     */
    @PostMapping("/update")
    @ApiOperation(value = "更新订单", tags = {"更新订单"}, notes = "更新订单")
    public JsonResult update(@RequestBody OrderUpdateReq req) {
        log.info("更新订单，入参: {}", JSON.toJSONString(req));
        if (StringUtils.isEmpty(req.getId()) && StringUtils.isEmpty(req.getOrderON())) {
            throw new ServiceException(MyErrorCode.ERROR_INPUT);
        }
        return orderService.update(req);
    }

    /**
     * crm回调更新优惠卷状态
     */
    @PostMapping("/updateState")
    @ApiOperation(value = "更新订单", tags = {"更新订单"}, notes = "更新订单")
    public JsonResult callBack(@RequestBody OrderCallBackReq req) {
        log.info("更新订单，入参: {}", JSON.toJSONString(req));
        return orderService.callBack(req);
    }

    @GetMapping("/export/order-item-excel")
    @ApiOperation("销售明细导出报表")
    public JsonResult exportOrderItemExcel(HttpServletResponse response, OrderQueryExcelReq req) {
        JsonResult jsonResult = new JsonResult();
        log.info("销售明细导出报表，入参: {}", JSON.toJSONString(req));
        try {
            Workbook workbook = orderService.exportOrderItemExcel(req);
            response.reset();
            response.setContentType("application/octet-stream");
            response.setCharacterEncoding("UTF-8");
            response.setHeader("Content-Disposition",
                "attachment;filename=\"" + new String("订单明细".getBytes(), "iso-8859-1")
                    + System.currentTimeMillis() + ".xls\"");
            response.setHeader("Connection", "close");
            OutputStream out = response.getOutputStream();
            workbook.write(out);
        } catch (IOException e) {
            log.error("# [订单明细]报表导出失败,msg = {}", e.getMessage(), e);
            jsonResult.setState(1);
            jsonResult.setMessage("[订单明细]报表导出失败");
            return jsonResult;
        }
        jsonResult.setState(0);
        jsonResult.setData("[销售明细]报表导出成功");
        return jsonResult;
    }

    /**
     * 查询已经兑换的优惠卷
     */
    @PostMapping("/coupon")
    @ApiOperation(value = "查询已经兑换的优惠卷", tags = {"优惠卷列表"}, notes = "优惠卷列表")
    public JsonResult coupon(@RequestBody CouponQueryReq req) {
        log.info("更新订单，入参: {}", JSON.toJSONString(req));
        if (null == req) {
            throw new ServiceException(MyErrorCode.ERROR_INPUT);
        }
        return orderService.coupon(req);
    }

    /**
     * 更新优惠卷过期状态
     */

    @PostMapping("/updateCoupon")
    @ApiOperation(value = "查询已经兑换的优惠卷", tags = {"优惠卷列表"}, notes = "优惠卷列表")
    public void updateCoupon(@RequestBody CouponQueryReq req) {
        log.info("更新订单，入参: {}", JSON.toJSONString(req));
        if (StringUtils.isBlank(req.getUserId())) {
            throw new ServiceException(MyErrorCode.ERROR_INPUT);
        }
        orderService.updateCoupon(req.getUserId());
    }


    /**
     * 新增库存扣减的方法
     */
        @PostMapping("/subStock")
    @ApiOperation(value = "新增库存扣减", tags = {"库存列表"}, notes = "创建库存兑换管理")
    public JsonResult subStock(@RequestBody OrderReq req) {
        log.info("创建订单管理，入参: {}", JSON.toJSONString(req));
        if (req == null) {
            throw new ServiceException(MyErrorCode.ERROR_INPUT);
        }
        return orderService.subStock(req);
    }


}
